/**
 * 装饰器：Include
 * @version:$Id: Include.js 37 2008-03-02 17:24:56Z dsonet $
 */

/**
 * @public
 * @decorator include
 * @attribute url
 * @attribute xpath
 * @attribute xslt
 */
function Include()
{
}
var $p = Type.extend(Include, Decorator).prototype;

$p.decorate = function()
{
	var url = this.attributes.get("url")
		, xslt = this.attributes.get("xslt")
		, decorator = this;
	$JSI.loadURL(url, function(req){
		if (req.readyState == 4)
		{
			//req.onreadystatechange = Function.prototype;
			var stus = req.status;
			if (stus >= 200 && stus < 300 || stus == 304 || !stus)
			{
				var result = req.responseText;
				if(xslt && XSLTProcessor)
				{
					$JSI.loadURL(xslt, function(req){
						if (req.readyState == 4)
						{
							var stus = req.status;
							if (stus >= 200 && stus < 300 || stus == 304 || !stus)
							{
								decorator.setContent(result, req.responseText);
							}
						}
					});
				}
				else {
					decorator.setContent(result);
				}
			}
		}
	
	});
}
$p.setContent = function(source, xslt)
{
	var xpath = this.attributes.get("xpath");

	if (xpath)
	{
		if (XPathEvaluator)
		{
			source = XPathEvaluator.selectNodes(toDocument(source).documentElement, xpath);
			if(!xslt)
			{
				if (source.length > 1)
				{
					for (var i = 0; i < source.length; i++)
					{
						this.appendContent(source.item(i));
					}
				}
				else
				{
					source = source.item(0);
				}
			}
		}
		else
		{
			$log.error("XPath is not support");
		}
	}

	if (xslt)
	{
		var xsltProcessor = new XSLTProcessor();
		xslt = toDocument(xslt);
		xsltProcessor.importStylesheet(xslt);
		var fragment = xsltProcessor.transformToFragment(toDocument(source), document);
		this.getContainer().appendChild(fragment);
	}
	else
	{
		this.appendContent(source);
	}
};

$p.appendContent = function(source)
{
	var container = this.getContainer();

	if (typeof source == "string")
	{
		container.innerHTML += source;
	}
	else
	{
		container.innerHTML += new XMLSerializer().serializeToString(source);
	}
}

function toDocument(source)
{
	if (typeof source == "string")
	{
		return new DOMParser().parseFromString(source, "text/xml");
	}
	else
	{
		return source;
	}
}
$p = null;